package cc.wanforme.chipmunity.system.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cc.wanforme.chipmunity.common.bean.WebResponse;
import cc.wanforme.chipmunity.system.event.BaseEvent;
import cc.wanforme.chipmunity.system.event.SubjectEvent;
import cc.wanforme.chipmunity.system.mapper.SubjectMapper;
import cc.wanforme.chipmunity.system.po.Subject;
import cc.wanforme.chipmunity.system.service.interfaces.SubjectService;

/**
 * @author wanne
 * 2019年8月17日
 * 
 */
@Service
public class SubjectServiceImpl implements SubjectService, ApplicationEventPublisherAware{
	private ApplicationEventPublisher publisher;
	
	@Autowired
	private SubjectMapper subjectMapper;
	
	@Override
	public WebResponse saveSubject(Subject subject) {
		if(StringUtils.isAnyBlank(subject.getSectionName(), subject.getSubjectname())) {
			return WebResponse.fail("信息不完整");
		}
		subjectMapper.insertSubject(subject);
		return WebResponse.success("主题添加成功");
	}
	
	@Override
	public WebResponse updateSubject(Subject subject) {
		if(subject.getId() == null) {
			return WebResponse.fail("未知主题");
		}
		
		if(StringUtils.isAnyBlank(subject.getSectionName(), subject.getSubjectname())) {
			return WebResponse.fail("不需要更新");
		}
		
		// 使用id作为主键，就不用管文章了
		subjectMapper.updateSubject(subject);
		return WebResponse.success("主题更新成功");
	}

	@Transactional
	@Override
	public WebResponse removeSubject(Long id) {
		if(id == null) {
			return WebResponse.fail("无效主题");
		}
		
		Subject subject = subjectMapper.selectSubject(id);
		publisher.publishEvent(new SubjectEvent(subject, BaseEvent.OperateType.DELETE));
		
		subjectMapper.deleteSubject(id);
		return WebResponse.success("主题删除成功");
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}
	
}
